package cn.e2win.biz.sms;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.e2win.base.controller.MyException;
import cn.e2win.base.entity.BaseEntity;
import cn.e2win.base.entity.Msg;
import cn.e2win.base.entity.MsgLogs;
import cn.e2win.base.entity.SysCompany;
import cn.e2win.base.json.vo.Pager;
import cn.e2win.biz.base.BaseDAO;
import cn.e2win.biz.base.BaseService;
import cn.e2win.biz.comm.SmsSender;


@Service
public class MsgService extends BaseService{
	

	@Autowired
	private MsgDao msgDao;
	
	@Override
	public BaseDAO initDao() {
		return msgDao;
	}

	public void pagerMsgLogs(Pager pager){
		msgDao.pagerMsgLogs(pager);
	}

	public void searchCust4SendMsg(Pager pager) {
		msgDao.pagerCust4SendMsg(pager);
	}
	@Transactional(rollbackFor=Exception.class)
	public MsgLogs sendSingleMsg(MsgLogs msgLog) throws MyException {
		//msgLog = (MsgLogs)super.edit(msgLog);
		if("SMS".equals(msgLog.getSendWay())){
			SmsSender send = new SmsSender(this, msgLog);
			send.sendNow();
		}
		msgLog = (MsgLogs)super.edit(msgLog);
		return msgLog;
	}

	@Transactional(rollbackFor=Exception.class)
	public Integer sendBatchMsg(Msg msg, List<MsgLogs> logList) throws MyException {
		Integer rInt = 0;
		msg = (Msg)super.edit(msg);
		for(MsgLogs log : logList){
			log.setMsgId(msg.getId());
			log.setMsgText(msg.getMsgText());
			log.setMsgType(msg.getMsgType());
			log = (MsgLogs)super.edit(log);
			SmsSender send = new SmsSender(this, log);
			send.sendByThread();
		}
		
		return rInt;
	}


	@Transactional(rollbackFor=Exception.class)
	public Integer updateCompanySmsQty(MsgLogs msgLog) throws MyException {
		int qty = 0;
		SysCompany company = getCompany(msgLog);
		if(company!=null && company.getSmsQty()!=null && msgLog.getQty()!=null){
			company.setSmsQty(company.getSmsQty()-msgLog.getQty());
			msgDao.merge(msgLog);
			msgDao.merge(company);
			qty = company.getSmsQty();
		}
		return qty;
	}
	
	public SysCompany getCompany(BaseEntity entity) throws MyException {
		SysCompany company  = (SysCompany) msgDao.getEntity(SysCompany.class, entity.getCoId());
		if(company==null){
			throw new MyException("程序异常");			
		}
		return company;
	}
}
